package com.ruixue.gatewayserver.filter;

import com.fasterxml.jackson.core.filter.TokenFilter;
import com.ruixue.gatewayserver.service.SsoMemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * 单点登录过滤器
 */
public class SsoLoginFilter implements GlobalFilter, Ordered {

    @Resource
    private SsoMemberService ssoMemberService;

    Logger logger= LoggerFactory.getLogger( TokenFilter.class );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入了单点登录过滤器。。。。");
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (token == null || token.isEmpty()) {
            logger.info( "token is empty..." );
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().toString();
        System.out.println("请求url:"+url);

        if (url.contains("userLogin/authUser") ||
                url.contains("memberLogin/authMember") ||
                (!StringUtils.isEmpty(token) &&
                        ssoMemberService.chechAccessToken(token))) {
            //放行
            return chain.filter(exchange);
        } else if (!StringUtils.isEmpty(token) &&
                !ssoMemberService.chechAccessToken(token)) {
            //不放行
            logger.info( "账号已在别处登陆..." );
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();

        } else {
//                //删除redis中的唯一识别
////                redisTemplate.delete(accessToken);
////                System.out.println("删除唯一识别");
                //不放行
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
        }

//        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
